<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Weekly_prize_m extends MY_Model {

	public function __construct()
	{
		parent::__construct();
		$this->load->library('module_helper');
	}
	
	function category_submit(){
		extract($this->input->post());
		
		$TOURNAMENT = $this->tournament_entity->init('id', $tournament_id);
		
		if(!isset($cat_id)){
			$tournament_starttime = $TOURNAMENT->getStartTime();
			$tournament_endtime = $TOURNAMENT->getEndTime();
			$starttimeInt = convertToTimeStampFromFormat($starttime);
			$endtimeInt = convertToTimeStampFromFormat($endtime);
			
			if($starttimeInt < $tournament_starttime){
				echo "Starttime must &gt; ".sysDateTimeFormat($tournament_starttime);
				exit();
			}
			if($endtimeInt > $tournament_endtime){
				echo "Endtime must &lt; ".sysDateTimeFormat($tournament_endtime);
				exit();
			}
			if(strlen($title)  == 0){
				echo "Title must not empty.";
				exit();
			}
			
			if($starttimeInt <= time() AND $endtimeInt >= time()){
				$status = 'Living';
			}else if($starttimeInt > time()){
				$status = 'Upcoming';
			}else if($endtimeInt < time()){
				$status = 'Closed';
			}
			
			$newid = $this->week_prize_entity->createNewEntity();
			$PRIZE = $this->week_prize_entity->init('id',$newid);
			$PRIZE->setTitle($title);
			$PRIZE->setStartTime($starttimeInt);
			$PRIZE->setEndTime($endtimeInt);
			$PRIZE->setTournamentId($tournament_id);
			$PRIZE->setEnable('no');
			$PRIZE->setStatus($status);
			$PRIZE->setIsCategory('yes');
			$PRIZE->update();
		}else{
			$tournament_starttime = $TOURNAMENT->getStartTime();
			$tournament_endtime = $TOURNAMENT->getEndTime();
			$starttimeInt = convertToTimeStampFromFormat($starttime);
			$endtimeInt = convertToTimeStampFromFormat($endtime);
			
			if($starttimeInt < $tournament_starttime){
				echo "Starttime must &gt; ".sysDateTimeFormat($tournament_starttime);
				exit();
			}
			if($endtimeInt > $tournament_endtime){
				echo "Endtime must &lt; ".sysDateTimeFormat($tournament_endtime);
				exit();
			}
			if(strlen($title)  == 0){
				echo "Title must not empty.";
				exit();
			}
			
			if($starttimeInt <= time() AND $endtimeInt >= time()){
				$status = 'Living';
			}else if($starttimeInt > time()){
				$status = 'Upcoming';
			}else if($endtimeInt < time()){
				$status = 'Closed';
			}
			
			$PRIZE = $this->week_prize_entity->init('id',$cat_id);
			$PRIZE->setTitle($title);
			$PRIZE->setStartTime($starttimeInt);
			$PRIZE->setEndTime($endtimeInt);
			$PRIZE->setTournamentId($tournament_id);
			$PRIZE->setStatus($status);
			$PRIZE->update();
		}
		$this->session->set_flashdata('success', lang('dataman.success'));
		echo 'ok';exit();
	}
	
	function changeEnablePrizeCate(){
		extract($this->input->post());
		$PRIZE = $this->week_prize_entity->init('id',$cat_id);
		$current = $PRIZE->getEnable();
		
		$this->db->where("tournament_id = {$PRIZE->getTournamentId()} AND enable = 'yes' ")->update(TBL_WEEKLY_PRIZE, array('enable'=>'no'));
		
		if($current == 'no'){
			$this->db->where("id = {$PRIZE->getId()}")->update(TBL_WEEKLY_PRIZE, array('enable'=>'yes'));
		} 
		$this->session->set_flashdata('success', lang('dataman.success'));
		echo 'ok';exit();
	}

	function prize_submit(){
		extract($this->input->post());
		
		if(!isset($_POST['id'])){
			if(! $this->phpvalidator->is_natural($rank) OR $rank <= 0){
				echo "Rank is not valid.";
				exit();
			}
			
			$PRIZE_CAT = clone_( $this->week_prize_entity->init('id',$cat_id) );
			$prize_id = clone_( $this->week_prize_entity->createNewEntity() );
			$PRIZE = clone_ ( $this->week_prize_entity->init('id', $prize_id) );
			$PRIZE->setTournamentId($PRIZE_CAT->getTournamentId());
			$PRIZE->setPrizeName($prize);
			$PRIZE->setWinnerId(0);
			$image = "";
			if(isset($_FILES["image"]) AND !empty($_FILES["image"]['name'])) {
				if(($_FILES["image"]['size']/1000000) > allowMaxFileSize() ){
					$image = '';
				}else{
					$image = $this->module_helper->uploadFile( 
											$_FILES["image"]['tmp_name'],
											$_FILES["image"]['name'],
											$PRIZE->getFolderFileStorage(),
											allowExtensionPictureUpload()
										);
				}	
			}
			$logo = "";
			if(isset($_FILES["logo"]) AND !empty($_FILES["logo"]['name'])) {
				if(($_FILES["logo"]['size']/1000000) > allowMaxFileSize() ){
					$logo = '';
				}else{
					$logo = $this->module_helper->uploadFile( 
											$_FILES["logo"]['tmp_name'],
											$_FILES["logo"]['name'],
											$PRIZE->getFolderFileStorage(),
											allowExtensionPictureUpload()
										);
				}	
			}
			$proof = "";
			if(isset($_FILES["proof"]) AND !empty($_FILES["proof"]['name'])) {
				if(($_FILES["proof"]['size']/1000000) > allowMaxFileSize() ){
					$proof = '';
				}else{
					$proof = $this->module_helper->uploadFile( 
											$_FILES["proof"]['tmp_name'],
											$_FILES["proof"]['name'],
											$PRIZE->getFolderFileStorage(),
											allowExtensionPictureUpload()
										);
				}	
			}
			$PRIZE->setRank($rank);
			$PRIZE->setCategoryId($cat_id);
			$PRIZE->setImage($image);
			$PRIZE->setLogo($logo);
			$PRIZE->setValue($value);
			$PRIZE->setCourierName($courier_name);
			$PRIZE->setShippingDate( convertToTimeStampFromFormat($shipping_date, 'Y-m-d') );
			$PRIZE->setTrackingNo($tracking_no);
			$PRIZE->setDescription($description);
			$PRIZE->setProof($proof);
			$PRIZE->setDeliveryStatus($delivery_status);
			$PRIZE->update();
			 
		}else{
			if(! $this->phpvalidator->is_natural($rank) OR $rank <= 0){
				echo "Rank is not valid.";
				exit();
			}
			$PRIZE = clone_ ( $this->week_prize_entity->init('id', $id) );
			$PRIZE->setPrizeName($prize);
			$PRIZE->setRank($rank);
			
			$image = $PRIZE->getImage();
			if(isset($_FILES["image"]) AND !empty($_FILES["image"]['name'])) {
				if(($_FILES["image"]['size']/1000000) > allowMaxFileSize() ){
					$image = '';
				}else{
					$image = $this->module_helper->uploadFile( 
											$_FILES["image"]['tmp_name'],
											$_FILES["image"]['name'],
											$PRIZE->getFolderFileStorage(),
											allowExtensionPictureUpload()
										);
				}	
			}
			$logo = $PRIZE->getLogo();
			if(isset($_FILES["logo"]) AND !empty($_FILES["logo"]['name'])) {
				if(($_FILES["logo"]['size']/1000000) > allowMaxFileSize() ){
					$logo = '';
				}else{
					$logo = $this->module_helper->uploadFile( 
											$_FILES["logo"]['tmp_name'],
											$_FILES["logo"]['name'],
											$PRIZE->getFolderFileStorage(),
											allowExtensionPictureUpload()
										);
				}	
			}
			$proof = $PRIZE->getProof();
			if(isset($_FILES["proof"]) AND !empty($_FILES["proof"]['name'])) {
				if(($_FILES["proof"]['size']/1000000) > allowMaxFileSize() ){
					$proof = '';
				}else{
					$proof = $this->module_helper->uploadFile( 
											$_FILES["proof"]['tmp_name'],
											$_FILES["proof"]['name'],
											$PRIZE->getFolderFileStorage(),
											allowExtensionPictureUpload()
										);
				}	
			}
			$PRIZE->setCategoryId($cat_id);
			$PRIZE->setLogo($logo);
			$PRIZE->setValue($value);
			$PRIZE->setImage($image);
			$PRIZE->setCourierName($courier_name);
			$PRIZE->setShippingDate( convertToTimeStampFromFormat($shipping_date, 'Y-m-d') );
			$PRIZE->setTrackingNo($tracking_no);
			$PRIZE->setDescription($description);
			$PRIZE->setProof($proof);
			$PRIZE->setDeliveryStatus($delivery_status);
			$PRIZE->update();
		}
		echo $cat_id;
		$this->session->set_flashdata('success', lang('dataman.success'));
		exit();
	}
	
	function delete_prize(){
		$this->db->where('id', $_POST['id'])->delete(TBL_WEEKLY_PRIZE);
		$this->session->set_flashdata('success', lang('dataman.success'));
		echo "ok";
		exit();
	}
	
	function finishWeeklyPrize(){
		$CAT_PRIZE = $this->week_prize_entity->init('id',$_POST['cat_id']);
		$listPrize = $this->week_prize_entity->getArrayListOfPrize($CAT_PRIZE->getId());
		
		foreach($listPrize as $item){
			$USER = $this->week_prize_entity->getUserObjectWithRank($item->rank, $item->tournament_id, $item->category_id);
			if($USER){
				$info =$this->week_prize_entity->getPersonWithARank($item->rank, $item->tournament_id, $item->category_id);
				$this->db->set('winner_id',$USER->getId().'#'.$info['point']);
				$this->db->where('id',$item->id)->update(TBL_WEEKLY_PRIZE);
				$this->email_sender->_sendEmailToUsers_notifyWeeklyPrizeFinished($item->id);
			}
		}
		$this->db->set('status','Finished');
		$this->db->set('enable','no');
		$this->db->where('id',$CAT_PRIZE->getId())->update(TBL_WEEKLY_PRIZE);
		
		$this->session->set_flashdata('success', lang('dataman.success'));
		exit();
	}
	
//endclass
}	